package com.lubase.metadata.tabletrigger;

import com.lubase.metadata.service.ZhPercentageService;
import com.lubase.model.DbEntity;
import com.lubase.model.DbTable;
import com.lubase.model.EDBEntityState;
import com.lubase.orm.extend.ITableTrigger;
import com.lubase.orm.util.TypeConverterUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MtTableTrigger implements ITableTrigger {
    @Override
    public String getTriggerTableCode() {
        return "mt_table";
    }

    @Override
    public String getTriggerName() {
        return "mt_table";
    }

    @Override
    public Boolean isEdit() {
        return true;
    }

    @Override
    public Boolean beforeValidate(DbTable tableInfo, DbEntity entity, Boolean isServer) throws Exception {
        if (entity.getDataState().equals(EDBEntityState.Modified)) {
            String tableCode = entity.get("table_code").toString();
            String tableName = TypeConverterUtils.object2String(entity.get("table_name"), "");
            String aliasName = TypeConverterUtils.object2String(entity.get("alias_name"), "");
            if (!StringUtils.isEmpty(aliasName)) {
                entity.put("merge_name", aliasName);
            } else if (!StringUtils.isEmpty(tableName)) {
                entity.put("merge_name", tableName);
            } else {
                entity.put("merge_name", tableCode);
            }
        }
        return true;
    }

    @Autowired
    ZhPercentageService zhPercentageService;

    @Override
    public void afterUpdate(DbTable tableInfo, DbEntity entity, Boolean isServer) throws Exception {
        if (entity.getDataState().equals(EDBEntityState.Modified)) {
            zhPercentageService.calculateZhPercentageOfTable(entity.getId().toString());
        }
    }
}
